package com.itheima.service;

import com.itheima.common.JsonResult;
import com.itheima.mapper.admin.CategoryMapper;
import com.itheima.mapper.admin.DishMapper;
import com.itheima.mapper.admin.SetmealMapper;
import com.itheima.pojo.admin.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.List;

/**
 * @author ChenJunJie
 * @date 2022/6/13 16:21
 * 分类service
 */
@Service
public class CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;


    //新增分类
    public JsonResult<String> categoryAdd(Category category) {


        Category isCategory = categoryMapper.categorySelectByNameAndType(category);
        if (isCategory != null) {
            return JsonResult.error(category.getName() + "已存在");
        }

        int i = categoryMapper.categoryAdd(category);

        if (i > 0) {
            return JsonResult.success("新增成功");
        } else {
            return JsonResult.success("新增失败");
        }
    }

    //按照分页查询分类
    public JsonResult<Pagination<Category>> categoryPagination(Integer pageNum, Integer pageSize) throws ParseException {

        Integer page = (pageNum - 1) * pageSize;

        List<Category> categories = categoryMapper.categorySelectAll();

        List<Category> categoriesByPagination = categoryMapper.categoryPagination(page, pageSize);



        Pagination<Category> eps = new Pagination<Category>();
        eps.setRecords(categoriesByPagination);
        eps.setTotal(categories.size());
        eps.setSize(pageSize);
        eps.setCurrent(pageNum);

        if (categories.size()<=0 || categoriesByPagination.size()<=0){
            return JsonResult.employeePaginationSuccess(eps,"查询失败,暂无数据");
        }

        return JsonResult.employeePaginationSuccess(eps,"查询成功");
    }

    //通过分类ID删除分类
    public JsonResult<String> categoryDeleteById(String id) {

        //判断菜品分类下是否有菜品，如果有则不能删除
        List<Dish<FlavorsById>> dishes = dishMapper.dishSelectByCategoryId(id);
        if (dishes.size()>0){
            return JsonResult.error("该菜品分类下已绑定菜品");
        }

        //判断套餐分类下是否有套餐，如果有则不能删除
        List<Setmeal<SetmealDish>> setmeals = setmealMapper.setmealSelectByCategoryId(id);
        if (setmeals.size()>0){
            return JsonResult.error("该套餐分类下已绑定套餐");
        }

        int i = categoryMapper.categoryDeleteById(id);

        if (i > 0) {
            return JsonResult.success("删除成功");
        } else {
            return JsonResult.error("删除失败");
        }
    }

    //通过分类id修改分类
    public boolean categoryUpdateById(Category category) {
        int i = categoryMapper.categoryUpdateById(category);

        return i > 0;
    }

    //通过分类类型查询分类
    public List<Category> categorySelectByType(Integer type){

        return categoryMapper.categorySelectByType(type);
    }
}
